/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcAddReceiptChannelActivity.java
 *   @Date: 19-2-1 下午1:41
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.adapter.OtcAppealAdapter;
import io.bhex.app.otc.adapter.OtcBankAdapter;
import io.bhex.app.otc.bean.AppealTypeBean;
import io.bhex.app.otc.presenter.OtcAddReceiptChannelPresenter;
import io.bhex.app.utils.FileTools;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.view.InputView;
import io.bhex.app.view.PopWindow;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.crop.ImgPickHandler;
import io.bhex.baselib.utils.crop.ImgPickHelper;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcPaymentChannelBean;
import io.bhex.sdk.otc.bean.OtcUploadImgResponse;
import io.bhex.sdk.otc.bean.OtcUserInfo;
import pub.devrel.easypermissions.EasyPermissions;

public class OtcAddReceiptChannelActivity extends BaseActivity<OtcAddReceiptChannelPresenter, OtcAddReceiptChannelPresenter.OtcAddReceiptChannelUI> implements OtcAddReceiptChannelPresenter.OtcAddReceiptChannelUI, View.OnClickListener, EasyPermissions.PermissionCallbacks {
    private static final int RECEIPT_UNION = 0;
    private static final int RECEIPT_ALI = 1;
    private static final int RECEIPT_WECHAT = 2;
    private TopBar topBar;
    private TextView nameTx;
    private EditText selectChannel;
    private EditText selectBankEt;
    private View bankCl;
    private InputView bankNoInput;
    private View aliOrWeCl;
    private InputView accountNoInput;
    private ImageView qrcodeImg;
    private TextView addQrCodeBtn;
    private InputView financePasswdInput;
    private int currentPaymentType;
//    private Map<Integer, OtcPaymentChannelBean> channelMap = new HashMap<>();
    private View channelListLayout;
    private RecyclerView recyclerViewChannelList;
    private PopWindow popWindowChannelList;
    private ArrayList<AppealTypeBean> channelListData;
    private List<OtcConfigResponse.BankBean> currentBankList;
//    private String realName;
    private OtcConfigResponse.BankBean selectBankBean;
    private View bankListLayout;
    private RecyclerView recyclerViewBankList;
    private PopWindow bankListPop;
    private AlertView selectPhotoAlert;
    private String[] selectPhotoWayArray;
    private String currentQRCodeUrl;
    private boolean isUpdateReceipt;
    private Button btnSure;
    private String[] channelListDataStr;
    private EditText nameEt;
    private OtcPaymentChannelBean updateReceiptBean;
    private InputView bankBranchInput;
    private String oldBankId;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_add_receipt_layout;
    }

    @Override
    protected OtcAddReceiptChannelPresenter createPresenter() {
        return new OtcAddReceiptChannelPresenter();
    }

    @Override
    protected OtcAddReceiptChannelPresenter.OtcAddReceiptChannelUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置禁止系统截屏、录制
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initView() {
        super.initView();
        channelListDataStr = new String[]{getString(R.string.string_pay_union), getString(R.string.string_pay_alipay), getString(R.string.string_pay_wechat)};
        selectPhotoWayArray = new String[]{getString(R.string.string_take_photo), getString(R.string.string_gallery)};
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        nameTx = viewFinder.textView(R.id.name);
        selectChannel = viewFinder.editText(R.id.selectChannel);
        selectBankEt = viewFinder.editText(R.id.selectBank);

        //银行
        bankCl = viewFinder.find(R.id.bankCl);
        bankNoInput = viewFinder.find(R.id.bankNo);
        bankBranchInput = viewFinder.find(R.id.bankBranch);
        //微信支付宝
        aliOrWeCl = viewFinder.find(R.id.aliOrWeCl);
        accountNoInput = viewFinder.find(R.id.accountNo);
        accountNoInput.setInputType(InputType.TYPE_CLASS_TEXT);
        qrcodeImg = viewFinder.imageView(R.id.qrcode);
        addQrCodeBtn = viewFinder.textView(R.id.btn_add_qrcode);
        financePasswdInput = viewFinder.find(R.id.financePasswd);
        btnSure = viewFinder.find(R.id.btn_sure);

        Intent intent = getIntent();
        if (intent != null) {
//            OtcPayChannelListResponse receiptListResponse = (OtcPayChannelListResponse) intent.getSerializableExtra("receiptList");
//            if (receiptListResponse != null) {
//                List<OtcPaymentChannelBean> receiptList = receiptListResponse.getArray();
//                if (receiptList != null) {
//                    for (OtcPaymentChannelBean otcPaymentChannelBean : receiptList) {
//                        channelMap.put(otcPaymentChannelBean.getPaymentType(), otcPaymentChannelBean);
//                    }
//                }
//
//            }
            updateReceiptBean = (OtcPaymentChannelBean) intent.getSerializableExtra("receipt");
            if (updateReceiptBean != null) {
                //修改支付方式 如果不为空 说明是修改收款方式
                isUpdateReceipt = true;
                switchChannelView(updateReceiptBean.getPaymentType(),updateReceiptBean);
            } else {
                //添加支付方式，默认银联
                isUpdateReceipt = false;
                switchChannelView(RECEIPT_UNION,null);
            }
        }

        //初始化渠道切换方式
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        channelListLayout = layoutInflater.inflate(R.layout.otc_appeal_type_layout, null, false);
        recyclerViewChannelList = channelListLayout.findViewById(R.id.recyclerView);

        popWindowChannelList = new PopWindow(this, channelListLayout, PixelUtils.getScreenWidth() - 2 * PixelUtils.dp2px(24), PixelUtils.dp2px(160));

        bankListLayout = layoutInflater.inflate(R.layout.otc_appeal_type_layout, null, false);
        recyclerViewBankList = bankListLayout.findViewById(R.id.recyclerView);

        bankListPop = new PopWindow(this, bankListLayout, PixelUtils.getScreenWidth() - 2 * PixelUtils.dp2px(24), PixelUtils.dp2px(360));

        initAppealTypeData();

    }

    /**
     * 切换添加收款渠道
     *
     * @param payType
     * @param receiptBean
     */
    private void switchChannelView(int payType,OtcPaymentChannelBean receiptBean) {
        currentPaymentType = payType;
        switchContentVisible(currentPaymentType);
        updateAddQrCodeBtnStatus(true);
        if(currentPaymentType<channelListDataStr.length){
            selectChannel.setText(channelListDataStr[currentPaymentType]);
        }

        if (receiptBean != null) {
            //如果不为空 说明是修改收款方式
            topBar.setTitle(getString(R.string.string_title_otc_modify_receipt_channel));
            btnSure.setText(getString(R.string.string_sure_modify));
            isUpdateReceipt = true;
            showOldReceiptInfo(receiptBean);

        } else {
            //默认银联
            topBar.setTitle(getString(R.string.string_title_otc_add_receipt_channel));
            btnSure.setText(getString(R.string.string_sure_add));
            isUpdateReceipt = false;

        }
    }


    private void showOldReceiptInfo(OtcPaymentChannelBean channelBean) {
        int paymentType = channelBean.getPaymentType();
        viewFinder.editText(R.id.name).setText(channelBean.getRealName());
        if (paymentType==RECEIPT_UNION) {
            oldBankId = channelBean.getBankName();
            selectBankBean = bankMap.get(channelBean.getBankName());
            if (selectBankBean != null) {
                selectBankEt.setText(selectBankBean.getName());
            }else{
                selectBankEt.setText(oldBankId);
            }
            bankNoInput.setInputString(channelBean.getAccountNo());
            bankBranchInput.setInputString(channelBean.getBranchName());
        }else{
            accountNoInput.setInputString(channelBean.getAccountNo());
            updateAddQrCodeBtnStatus(false);
            currentQRCodeUrl = channelBean.getQrcode();
            String url = channelBean.getQrcode();
            if (!TextUtils.isEmpty(url)) {
                if (url.startsWith("/")) {
                    url = url.replaceFirst("/", "");
                }
            }
            url = UrlsConfig.API_OTC_URL+url;
            Glide.with(OtcAddReceiptChannelActivity.this)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .into(qrcodeImg);

        }

    }

    /**
     * 切换中间内容view
     *
     * @param currentPaymentType
     */
    private void switchContentVisible(int currentPaymentType) {
        if (currentPaymentType == RECEIPT_UNION) {
            //银联
            bankCl.setVisibility(View.VISIBLE);
            aliOrWeCl.setVisibility(View.GONE);
        } else {
            bankCl.setVisibility(View.GONE);
            aliOrWeCl.setVisibility(View.VISIBLE);
            if (currentPaymentType==RECEIPT_ALI) {
                //支付宝
                accountNoInput.setInputHint(getString(R.string.string_otc_account_ali));
            }else{
                //微信
                accountNoInput.setInputHint(getString(R.string.string_otc_account_wechat));
            }
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.selectChannel).setOnClickListener(this);
        viewFinder.find(R.id.selectBank).setOnClickListener(this);
        viewFinder.find(R.id.btn_add_qrcode).setOnClickListener(this);
        viewFinder.find(R.id.btn_sure).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.selectChannel:
                //选择通道
                if (!isUpdateReceipt) {
                    if (channelListData != null) {
                        showChannelListPop(channelListData);
                    }
                }
                break;
            case R.id.selectBank:
                //选择开户行
//                if (currentBankList != null) {
//                    showBankListPop(currentBankList);
//                }
                break;
            case R.id.btn_add_qrcode:
                //上传二维码
                showSelectPhoto();
                break;
            case R.id.btn_sure:
                nameEt = viewFinder.editText(R.id.name);
                String name = nameEt.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getString(R.string.string_name_is_not_empty));
                    return;
                }
                //确认按钮
                if (currentPaymentType == RECEIPT_UNION) {
                    //银联
                    String bankName = selectBankEt.getText().toString().trim();
                    if (TextUtils.isEmpty(bankName)) {
                        ToastUtils.showShort(getString(R.string.string_hint_enter_the_bank));
                        return;
                    }
                    String bankNO = bankNoInput.getInputString();
                    if (TextUtils.isEmpty(bankNO)) {
                        ToastUtils.showShort(getString(R.string.string_input_bank_no_please));
                        return;
                    }

                    String bankBranch = bankBranchInput.getInputString();

                    String passwd = financePasswdInput.getInputString();
                    if (TextUtils.isEmpty(passwd)) {
                        ToastUtils.showShort(getString(R.string.string_input_please) + getString(R.string.string_finance_passwd));
                        return;
                    }
                    if (isUpdateReceipt) {
                        if (updateReceiptBean == null) {
                            ToastUtils.showShort(getString(R.string.string_net_exception));
                            return;
                        }
                    }
                    /**银行卡******/
                    getPresenter().setReceiptChannel(isUpdateReceipt, updateReceiptBean, name, currentPaymentType, bankName,bankBranch, bankNO, currentQRCodeUrl, passwd);

                } else {
                    if (TextUtils.isEmpty(currentQRCodeUrl)) {
                        ToastUtils.showShort(getString(R.string.string_add_qrcode_please));
                        return;
                    }
                    String accountNo = accountNoInput.getInputString();
                    if (TextUtils.isEmpty(accountNo)) {
                        ToastUtils.showShort(getString(R.string.string_input_please) + getString(currentPaymentType == RECEIPT_ALI ? R.string.string_otc_account_ali : R.string.string_otc_account_wechat));
                        return;
                    }

                    String passwd = financePasswdInput.getInputString();
                    if (TextUtils.isEmpty(passwd)) {
                        ToastUtils.showShort(getString(R.string.string_input_please) + getString(R.string.string_finance_passwd));
                        return;
                    }
                    if (isUpdateReceipt) {
                        if (updateReceiptBean == null) {
                            ToastUtils.showShort(getString(R.string.string_net_exception));
                            return;
                        }
                    }
                    /**二维码支付方式******/
                    getPresenter().setReceiptChannel(isUpdateReceipt,updateReceiptBean, name, currentPaymentType, "","", accountNo, currentQRCodeUrl, passwd);
                }

                break;
        }
    }

    @Override
    public void showOtcUserInfo(OtcUserInfo response) {
//        realName = response.getRealName();
//        if (!TextUtils.isEmpty(realName)) {
//            nameTx.setText(realName);
//        }
    }

    private HashMap<String,OtcConfigResponse.BankBean> bankMap = new HashMap<>();
    @Override
    public void showBankList(List<OtcConfigResponse.BankBean> bankList) {
        currentBankList = bankList;
        if (currentBankList != null) {
            bankMap.clear();
            for (OtcConfigResponse.BankBean bankBean : currentBankList) {
                bankMap.put(bankBean.getBankId(),bankBean);
            }
            //如果是银行  有默认银行选项，则设置默认银行选项
            if (!TextUtils.isEmpty(oldBankId)) {
                selectBankBean = bankMap.get(oldBankId);
                if (selectBankBean != null) {
                    selectBankEt.setText(selectBankBean.getName());
                }else{
                    selectBankEt.setText(oldBankId);
                }
            }
        }
    }

    /**
     * 显示银行列表
     *
     * @param data
     */
    private void showBankListPop(List<OtcConfigResponse.BankBean> data) {
        if (data != null) {

            OtcBankAdapter bankAdapter = new OtcBankAdapter(data);
            bankAdapter.isFirstOnly(false);
            recyclerViewBankList.setLayoutManager(new LinearLayoutManager(this));
            recyclerViewBankList.setItemAnimator(new DefaultItemAnimator());
            recyclerViewBankList.setAdapter(bankAdapter);

            bankAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    bankListPop.dismiss();
                    List<OtcConfigResponse.BankBean> data = adapter.getData();
                    selectBankBean = data.get(position);
                    if (selectBankBean != null) {
                        String bankName = selectBankBean.getName();
                        if (!TextUtils.isEmpty(bankName)) {
                            selectBankEt.setText(bankName);
                        }
                    }
                }
            });
            bankListPop.showAsDropDown(selectBankEt);
        }
    }

    private void initAppealTypeData() {
        channelListData = new ArrayList<>();
        for (int i = 0; i < channelListDataStr.length; i++) {
            AppealTypeBean appealTypeBean = new AppealTypeBean();
            appealTypeBean.setAppealType(i);
            appealTypeBean.setAppealTheme(channelListDataStr[i]);
            channelListData.add(appealTypeBean);
        }

    }

    /**
     * 显示收款方式列表
     *
     * @param channelListData
     */
    private void showChannelListPop(List<AppealTypeBean> channelListData) {
        if (channelListData != null) {

            OtcAppealAdapter otcAppealAdapter = new OtcAppealAdapter(channelListData);
            otcAppealAdapter.isFirstOnly(false);
//            otcSwitchBAdapterBuy.setEmptyView(emptyView);
            recyclerViewChannelList.setLayoutManager(new LinearLayoutManager(this));
            recyclerViewChannelList.setItemAnimator(new DefaultItemAnimator());
            recyclerViewChannelList.setAdapter(otcAppealAdapter);

            otcAppealAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    popWindowChannelList.dismiss();
                    List<AppealTypeBean> data = adapter.getData();
                    AppealTypeBean appealTypeBean = data.get(position);
                    if (appealTypeBean != null) {
                        int payType = appealTypeBean.getAppealType();
                        if (currentPaymentType != payType) {
                            switchChannelView(payType, null);
                            selectChannel.setText(appealTypeBean.getAppealTheme());
                        }
                    }
                }
            });
            popWindowChannelList.showAsDropDown(selectChannel);
        }
    }


    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImgPickHelper.getInstance().handleResult(this, requestCode, resultCode, data);
    }


    private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x0;
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 0x2;

    /**
     * 选择图片
     */
    private void showSelectPhoto() {
        if (selectPhotoAlert != null && selectPhotoAlert.isShowing())
            return;
        if (accountNoInput != null) {
            KeyBoardUtil.closeKeybord(accountNoInput.getEditText(),this);
        }
        selectPhotoAlert = new AlertView(null, null, getString(R.string.string_cancel), null, selectPhotoWayArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position == 0) {
                    //拍照
                    startSelectImage(true);
                } else {
                    //从相册选择
                    startSelectImage(false);
                }
            }
        });
        selectPhotoAlert.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
            }
        });
        selectPhotoAlert.show();
    }

    private void startSelectImage(boolean bCamera) {
//        ImgPickHelper.getInstance().clearCachedCropFile(AuthenticateSubmitActivity.this);
        ImgPickHelper.getInstance().registeHandler(new ImgPickHandler() {

            @Override
            public void onSuccess(Uri uri) {
                uploadImage(uri);
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFailed(String message) {


            }
        });
        ImgPickHelper.getInstance().needCrop(false);
        if (bCamera) {
            String[] perms = {Manifest.permission.CAMERA};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), CAMERA_PERMISSION_REQUEST_CODE, perms);
            } else {
                ImgPickHelper.getInstance().goCamera(this);
            }

            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goCamera(getActivity());
            }*/

        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            } else {
                ImgPickHelper.getInstance().goGallery(this);
            }
            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goGallery(getActivity());
            }*/
        }

    }

    private void uploadImage(final Uri fromUri) {
        if (fromUri == null)
            return;
        if (FileTools.fileIsExists(fromUri.getPath())) {
            //if(mJSImageCallback != null){
            getPresenter().uploadImage(fromUri.getPath(), new SimpleResponseListener<OtcUploadImgResponse>() {

                @Override
                public void onBefore() {
                    super.onBefore();
                    getUI().showProgressDialog("", getString(R.string.string_uploading));
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    getUI().dismissProgressDialog();
                }

                @Override
                public void onSuccess(OtcUploadImgResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, true)) {
                        updateAddQrCodeBtnStatus(false);
                        currentQRCodeUrl = response.getUrl();
                        Glide.with(OtcAddReceiptChannelActivity.this)
                                .load(fromUri.getPath())
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .skipMemoryCache(true)
                                .into(qrcodeImg);

                        ToastUtils.showLong(OtcAddReceiptChannelActivity.this, getString(R.string.string_upload_success));

                    }
                }

                @Override
                public void onError(Throwable error) {
                    ToastUtils.showLong(OtcAddReceiptChannelActivity.this, getString(R.string.string_upload_failed));
                }

            });
        }
    }

    private void updateAddQrCodeBtnStatus(boolean isAddNew) {
        if (isAddNew) {
            //重置信息
            selectBankBean = null;
            selectBankEt.setText("");
            bankNoInput.setInputString("");
            bankBranchInput.setInputString("");
            accountNoInput.setInputString("");
            currentQRCodeUrl = "";

            qrcodeImg.setVisibility(View.GONE);
            addQrCodeBtn.setText(getString(R.string.string_otc_qrcode_add));
            addQrCodeBtn.setCompoundDrawables(null, this.getResources().getDrawable(R.mipmap.icon_add), null, null);
        } else {
            addQrCodeBtn.setText(getString(R.string.string_otc_qrcode_modify));
            qrcodeImg.setVisibility(View.VISIBLE);
            addQrCodeBtn.setCompoundDrawables(null, this.getResources().getDrawable(R.mipmap.icon_refresh), null, null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        requestCodeQRCodePermissions();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(this);
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(this);
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ImgPickHelper.getInstance().unregistHandler();
    }

}
